import express from 'express';
const app = express();
const PORT = process.env.PORT || 7890;

const headers = {
    'Content-Type': 'text/event-stream',
    'Connection': 'keep-alive',
    'Cache-Control': 'no-cache'
}
let n = 1
app.post('/events', (req, res) => {
    console.log('req', req);
    res.writeHead(200, headers);

    const sendEvent = (data) => {
        // 所有数据都必须以'data:'开头
        const formattedData = `data: ${JSON.stringify(data)}\n\n`;
        res.write(formattedData);
    };

    // 每两秒发送一个事件
    const intervalId = setInterval(() => {
        const message = {
            time: new Date().toTimeString(),
            message: '服务端产生的数据',
        };
        n += 1
        if (n <= 4) {
            sendEvent(message);
        } else {
            n = 1
            clearInterval(intervalId);
            res.end();
        }
    }, 2000);

    // 关闭轮询
    req.on('close', () => {
        clearInterval(intervalId);
        res.end();
    });
});
app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));